/**
 * 功能权限管理
 */

PrivilegeManager = function() {
	this.init();
	this.doLayout();
};

PrivilegeManager.prototype = {

	rootRole : new Ext.tree.TreeNode({text : Gfa.CommonUtil.matchLanguage(system.Role.Role)}),

	rootModule : new Ext.tree.AsyncTreeNode(),

	init : function() {
		var rpcList = [];
		rpcList["menuGroup"] = {
			rpc : {
				service : PrivilegeService,
				method : "loadMenuGroups"
			},
			createNodeConfig : function(menuGroup) {
				var nodeConfig = {
					id : "menuGroup-" + menuGroup.menuGroupId,
					text : menuGroup.menuGrpTitleKey,
					iconCls : "menuGroup",
					checked : false,
					rpcParams : [menuGroup.menuGroupId],
					rpc : rpcList["menuItem"].rpc,
					gfaData : menuGroup
				};
				return nodeConfig;
			}
		};
		rpcList["menuItem"] = {
			rpc : {
				service : PrivilegeService,
				method : "loadMenuItems"
			},
			createNodeConfig : function(menuItem) {
				var treeRole = Ext.getCmp('treeRole');
				var checked = false;
				if (treeRole.selModel.selNode && !treeRole.selModel.selNode.isRoot) {
					var roleMenuItems = treeRole.selModel.selNode.roleMenuItems;
					if (roleMenuItems) {
						Ext.each(roleMenuItems, function(rmi) {
							if (rmi.menuItemId == menuItem.menuItemId)
								checked = true;
						});
					}
				}
				var nodeConfig = {
					id : "menuItem-" + menuItem.menuItemId,
					text : menuItem.menuItemTitleKey,
					iconCls : "menuItem",
					checked : checked,
					rpcParams : [menuItem.menuItemId],
					rpc : rpcList["viewButton"].rpc,
					gfaData : menuItem
				};
				return nodeConfig;
			}
		};
		rpcList["viewButton"] = {
			rpc : {
				service : PrivilegeService,
				method : "loadViewButtons"
			},
			createNodeConfig : function(viewButton) {
				var treeRole = Ext.getCmp('treeRole');
				var checked = false;
				if (treeRole.selModel.selNode && !treeRole.selModel.selNode.isRoot) {
					var roleMenuItems = treeRole.selModel.selNode.roleMenuItems;
					if (roleMenuItems) {
						Ext.each(roleMenuItems, function(rmi) {
							Ext.each(rmi.roleMenuButtons, function(rmb) {
								if (rmb.viewButtonId == viewButton.viewButtonId)
									checked = true;
							});
						});
					}
				}
				var nodeConfig = {
					id : "viewButton-" + viewButton.viewButtonId,
					text : viewButton.btnTitleKey,
					iconCls : "viewButton",
					checked : checked,
					leaf : true,
					gfaData : viewButton
				};
				return nodeConfig;
			}
		};
		var loader = new Gfa.data.RPCTreeLoader({
			createNodeConfig : function(model) {
				if (model.menuGrpTitleKey) {
					return rpcList["menuGroup"].createNodeConfig(model);
				} else if (model.menuItemTitleKey) {
					return rpcList["menuItem"].createNodeConfig(model);
				} else if (model.btnTitleKey) {
					return rpcList["viewButton"].createNodeConfig(model);
				}
			}
		});

		var rootRole = this.rootRole;
		var rootModule = this.rootModule;

		CommonService.loadAll('com.wef.system.entity.Role', function(roles) {
			// TODO 改成只预先加载第一个节点的roleMenuItems,其他节点点击后才加载
			Ext.each(roles, function(role) {
				var node = new Ext.tree.TreeNode({
					id : role.roleId,
					text : role.roleName,
					allowDrag : false
				});
				rootRole.appendChild(node);
			});
			rootRole.expand();
		});

		CommonService.loadAll('com.wef.system.entity.Module', function(modules) {
			// load module
			Ext.each(modules, function(md) {
				var mdNode = new Ext.tree.AsyncTreeNode({
					id : 'module-' + md.moduleId,
					text : Gfa.CommonUtil.matchLanguage(md.moduleTitleKey),
					iconCls : 'module',
					expanded : true,
					checked : false,
					loader : loader,
					rpcParams : [md.moduleId],
					rpc : rpcList["menuGroup"].rpc
				});
				mdNode.gfaData = md;
				rootModule.appendChild(mdNode);
			});
		});
		this.panel = new Ext.Panel({
			layout : 'border',
			border : false,
			defaultType : 'treepanel',
			defaults : {
				border : true,
				autoScroll : true
			},
			tbar : [' ', '-', {
				id : 'privilege-save',
				text : Gfa.CommonUtil
						.matchLanguage(i18n.global.save),
				iconCls : 'toolbar-save',
				scope : this,
				handler : this.saveRoleMenuWithButtons
			}, '-'],
			items : [{
				id : 'treeRole',
				region : 'west',
				width : 250,
				animate : true,
				rootVisible : true,
				split : true,
				margins : '5 0 5 5',
				root : this.rootRole
			}, {
				id : 'treeModule',
				region : 'center',
				animate : false,
				rootVisible : false,
				margins : '5 5 5 0',
				root : this.rootModule
			}]
		});

		var treeRole = Ext.getCmp('treeRole');
		var treeModule = Ext.getCmp('treeModule');

		treeRole.on('click', function(node) {
			if (treeModule.disabled)
				treeModule.enable();
			if (node.isRoot)
				return;
			this.initPrivilege(node);
		}, this);

		treeModule.on('checkchange', function(node, checked) {
			if (Ext.getCmp('privilege-save').disabled) {
				Ext.getCmp('privilege-save').enable();
			}

			var thisThis = this;
			node.cascade(function(childNode) {
				if (!childNode.rendered)
					childNode.render();

				if (checked == false) {
					if (childNode.getUI().isChecked()) {
						childNode.getUI().toggleCheck(checked);
						thisThis.setGfaDataRowStatus(childNode, checked);
					}
				} else {
					if (!childNode.getUI().isChecked()) {
						childNode.getUI().toggleCheck(checked);
						thisThis.setGfaDataRowStatus(childNode, checked);
					}
				}
			});
			treeModule.suspendEvents();
			node.bubble(function(parentNode) {
				if (checked == true) {
					if (!parentNode.getUI().isChecked()) {
						parentNode.getUI().toggleCheck(checked);
						thisThis.setGfaDataRowStatus(parentNode, checked);
					}
				}
			});
			treeModule.resumeEvents();
			// 修改node.attributes.gfaData的rowStatus
			this.setGfaDataRowStatus(node, checked);
		}, this);
	},

	setGfaDataRowStatus : function(node, checked) {
		var obj = node.attributes.gfaData;
		if (!obj)
			return;
		if (obj.rowStatus == Gfa.GlobalConstant.ROWSTATUS_UNCHANGED) {
			if (checked) {
				obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
			} else {
				obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_DELETED;
			}
		}
		if (obj.rowStatus == Gfa.GlobalConstant.ROWSTATUS_ADDED) {
			if (!checked) {
				obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_UNCHANGED;
			}
		}
		if (obj.rowStatus == Gfa.GlobalConstant.ROWSTATUS_DELETED) {
			if (checked) {
				obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_UNCHANGED;
			}
		}
	},

	initPrivilege : function(node) {
		var thisThis = this;
		PrivilegeService.loadRoleMenuItemByRoleId(node.id, {
			callback : function(result) {
				node.roleMenuItems = result;
				thisThis.initChecked(node);
				thisThis.initAllNodeRowStatus(thisThis.rootModule);
			},
			async : false
		});
	},

	initChecked : function(node) {

		this.rootModule.cascade(function(node) {
			node.getUI().toggleCheck(false);
		});

		var treeModule = Ext.getCmp('treeModule');

		Ext.each(node.roleMenuItems, function(rmi) {
			var miNode = treeModule.getNodeById("menuItem-" + rmi.menuItem.menuItemId);
			if (!miNode) {
				return;
			}
			if (!miNode.rendered) {
				miNode.render();
			}

			treeModule.suspendEvents();

			miNode.getUI().toggleCheck(true);
			miNode.bubble(function(parentNode) {
				parentNode.getUI().toggleCheck(true);
			});

			Ext.each(rmi.roleMenuButtons, function(rmb) {
				var vbNode = treeModule.getNodeById("viewButton-" + rmb.viewButton.viewButtonId);
				if (vbNode) {
					if (!vbNode.rendered)
						vbNode.render();

					vbNode.getUI().toggleCheck(true);
				}
			});
			treeModule.resumeEvents();
		});
	},

	saveRoleMenuWithButtons : function() {
		var treeRole = Ext.getCmp('treeRole');
		var roleNode = treeRole.selModel.selNode;

		if (!treeRole.selModel.selNode)
			return;

		var roleMenuItems = [];
		this.panel.el.mask(i18n.message.saveing, 'x-mask-loading');
		this.readCheckedNodeInfo(this.rootModule, roleMenuItems);
		var thisThis = this;
		if (roleMenuItems.length == 0) {
			thisThis.panel.el.unmask();
			Ext.Msg.alert(Gfa.CommonUtil.matchLanguage(i18n.message.msg), i18n.message.noChanges);
			Ext.getCmp('privilege-save').disable();
			return;
		}
		PrivilegeService.saveRoleMenuWithButtons(roleNode.id, roleMenuItems, {
			callback : function(result) {
				Ext.Msg.alert(Gfa.CommonUtil.matchLanguage(i18n.message.msg), Gfa.CommonUtil.matchLanguage(i18n.message.saveSucceed));
				thisThis.initAllNodeRowStatus(thisThis.rootModule);
				Ext.getCmp('privilege-save').disable();
				thisThis.panel.el.unmask();
			},
			errorHandler : function(msg) {
				Ext.Msg.alert(Gfa.CommonUtil.matchLanguage(i18n.message.msg), msg)
				thisThis.panel.el.unmask();
			},
			async : true
		});
	},

	/**
	 * 所有Node的rowStatus设置为ROWSTATUS_UNCHANGED
	 */
	initAllNodeRowStatus : function(node) {
		if (node.isLeaf())
			return;
		var type = node.id.split("-")[0];
		if (type === "menuItem") {
			node.attributes.gfaData.rowStatus = Gfa.GlobalConstant.ROWSTATUS_UNCHANGED
			for (var i = 0; i < node.childNodes.length; i++) {
				node.childNodes[i].attributes.gfaData.rowStatus = Gfa.GlobalConstant.ROWSTATUS_UNCHANGED;
			}
		} else {
			for (var j = 0; j < node.childNodes.length; j++) {
				for (var k = 0; k < node.childNodes[j].childNodes.length; k++) {
					for (var i = 0; i < node.childNodes[j].childNodes[k].childNodes.length; i++) {
						this.initAllNodeRowStatus(node.childNodes[j].childNodes[k].childNodes[i]);
					}
				}
			}
		}
	},

	readCheckedNodeInfo : function(node, roleMenuItems) {
		if (node.isLeaf())
			return;

		var type = node.id.split("-")[0];

		if (type === "menuItem") {
			var roleMenuButtons = [];
			var menuItem = node.attributes.gfaData;
			menuItem.roleMenuButtons = [];
			var mbChange = false;
			for (var i = 0; i < node.childNodes.length; i++) {
				if (node.childNodes[i].attributes.gfaData.rowStatus != Gfa.GlobalConstant.ROWSTATUS_UNCHANGED) {
					menuItem.roleMenuButtons.push(node.childNodes[i].attributes.gfaData);
					mbChange = true;
				}
			}

			if (node.attributes.gfaData.rowStatus != Gfa.GlobalConstant.ROWSTATUS_UNCHANGED
					|| mbChange) {
				roleMenuItems.push(menuItem);
			}
		} else {
			for (var j = 0; j < node.childNodes.length; j++) {
				for (var k = 0; k < node.childNodes[j].childNodes.length; k++) {
					if (node.childNodes[j].childNodes[k] && node.childNodes[j].childNodes[k].childNodes) {
						for (var i = 0; i < node.childNodes[j].childNodes[k].childNodes.length; i++) {
							this.readCheckedNodeInfo(node.childNodes[j].childNodes[k].childNodes[i],
									roleMenuItems);
						}
					}
				}
			}
		}
	},

	doLayout : function() {
		var renderTo = Ext.getCmp(Gfa.GlobalVariable.contentAreaId).activeTab;
		renderTo.add(this.panel);
		renderTo.doLayout();
		Ext.getCmp('privilege-save').disable();
	}
};

Ext.onReady(function(){
	new PrivilegeManager();
});